const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = db.command
let userInfo=null


exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const orders = await db.collection("order").where({
    state: _.or(_.eq(0), _.eq(1)),
  }).orderBy("audit_time", "desc").limit(20).get()

  const res = await Promise.all([
    userInfo = await db.collection("user").where({ openid: wxContext.OPENID }).get()
  ])
  if (userInfo.data.length == 0) {
    return {
      code: 401,
      data: {},
      msg: "have not login"
    }
  }
    if (userInfo.data[0].status != 0&&userInfo.data[0].status != 1) {
      return {
        code: 401,
        data: {},
        msg: "no privilege",
        userInfo: userInfo
      }
    }
    if (orders.data.length == 0) {
      return {
        code: 404,
        data: {},
        masg: "empty result"
      }
    }

    return {
      code: 200,
      data: orders.data,
      msg: "success"

    }
  }